<template>
	<gradient-background>
		<view class="container">
			<view class="content">
				<!-- 结果标题 -->
				<view class="result-header">
					<text class="result-title">占卜结果</text>
					<text class="result-subtitle">{{ typeText }}结果</text>
				</view>
				
				<!-- 问题显示 -->
				<app-card>
					<view class="question-display">
						<text class="question-label">您的问题</text>
						<text class="question-text">{{ question }}</text>
						<text class="question-meta" v-if="metaInfo">{{ metaInfo }}</text>
					</view>
				</app-card>
				
				<!-- 卦象显示 -->
				<app-card :clickable="true" @tap="viewHexagramDetail" v-if="hexagram">
					<view class="hexagram-display">
						<view class="hexagram-visual">
							<view class="hexagram-symbols">
								<text class="symbol-text">{{ hexagram.fullSymbol }}</text>
							</view>
							<view class="hexagram-info">
								<text class="hexagram-name">{{ hexagram.name }}</text>
								<text class="element-relation">{{ hexagram.elementRelation }}</text>
							</view>
						</view>
						<view class="hexagram-description">
							<text class="description-text">{{ hexagram.description }}</text>
						</view>
						<view class="view-detail-hint">
							<text class="hint-text">点击查看详细解读 →</text>
						</view>
					</view>
				</app-card>
							
				<!-- 卦象加载中或错误状态 -->
				<app-card v-else>
					<view class="error-display">
						<text class="error-text">卦象数据加载失败，请重新起卦</text>
					</view>
				</app-card>
				
				<!-- 简要解读 -->
				<app-card v-if="hexagram">
					<view class="interpretation">
						<text class="interpretation-title">简要解读</text>
						<text class="interpretation-text">{{ simpleInterpretation }}</text>
					</view>
				</app-card>
				
				<!-- 操作按钮 -->
				<view class="actions">
					<!-- 主要操作按钮 -->
					<view class="primary-action">
						<view class="action-button primary-button" @tap="viewHexagramDetail" :class="{ disabled: !hexagram }">
							<view class="button-icon">📖</view>
							<view class="button-content">
								<text class="button-title">查看详细解读</text>
								<text class="button-desc">深入了解卦象含义</text>
							</view>
							<view class="button-arrow">→</view>
						</view>
					</view>
					
					<!-- 次要操作按钮 -->
					<view class="secondary-actions">
						<view class="action-button secondary-button" @tap="restartDivination">
							<view class="button-icon">🔄</view>
							<view class="button-content">
								<text class="button-title">重新起卦</text>
								<text class="button-desc">开始新的占卜</text>
							</view>
						</view>
						
						<view class="action-button secondary-button" @tap="showShareOptions" :class="{ disabled: !hexagram }">
							<view class="button-icon">📤</view>
							<view class="button-content">
								<text class="button-title">分享结果</text>
								<text class="button-desc">分享给朋友</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 分享选项弹窗 -->
				<view class="share-modal" v-if="showShareModal" @tap="hideShareOptions">
					<view class="share-content" @tap.stop>
						<view class="share-header">
							<text class="share-title">分享占卜结果</text>
							<view class="close-btn" @tap="hideShareOptions">✕</view>
						</view>
						<view class="share-options">
							<view class="share-option" @tap="handleShareToFriend">
								<view class="share-icon">💬</view>
								<text class="share-text">微信好友</text>
							</view>
							<view class="share-option" @tap="handleShareToMoments">
								<view class="share-icon">🌟</view>
								<text class="share-text">朋友圈</text>
							</view>
							<view class="share-option" @tap="handleCopyLink">
								<view class="share-icon">🔗</view>
								<text class="share-text">复制链接</text>
							</view>
							<view class="share-option" @tap="handleGeneratePoster">
								<view class="share-icon">🖼️</view>
								<text class="share-text">生成海报</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 分享模板 -->
				<share-template
					:visible="showShareTemplate"
					:cardType="shareTemplateType"
					:hexagram="hexagram"
					:question="question"
					:interpretation="simpleInterpretation"
					:showCanvas="showCanvas"
					@close="closeShareTemplate"
					ref="shareTemplate"
				></share-template>
			</view>
		</view>
	</gradient-background>
</template>

<script>
import GradientBackground from '@/components/gradient-background/gradient-background.vue'
import AppCard from '@/components/app-card/app-card.vue'
import AppButton from '@/components/app-button/app-button.vue'
import ShareButton from '@/components/share-button/share-button.vue'
import ShareTemplate from '@/components/share-template/share-template.vue'
import { Hexagram } from '@/utils/hexagram-service.js'
import { ShareService } from '@/utils/share-service.js'
import apiService from '@/utils/api-service.js'

export default {
	name: 'DivinationResultPage',
	components: {
		GradientBackground,
		AppCard,
		AppButton,
		ShareButton,
		ShareTemplate
	},
	data() {
		return {
			type: '',
			question: '',
			hexagram: null,
			metaInfo: '',
			navigating: false, // 防止重复导航
			typeTexts: {
				voice: '语音起卦',
				photo: '拍照起卦',
				time: '时间起卦',
				number: '数字起卦'
			},
			shareService: null,
			showShareTemplate: false,
			shareTemplateType: 'default',
			showCanvas: false,
			showShareModal: false
		}
	},
	computed: {
		typeText() {
			return this.typeTexts[this.type] || '起卦';
		},
		simpleInterpretation() {
			if (!this.hexagram) return '';
			
			// 根据卦象生成简要解读
			const elementRelation = this.hexagram.elementRelation;
			let interpretation = `此卦为"${this.hexagram.name}"，`;
			
			switch (elementRelation) {
				case '比和':
					interpretation += '上下卦五行相同，表示事情发展平稳，宜顺势而为。';
					break;
				case '生发':
					interpretation += '上下卦五行相生，表示事情发展向好，有贵人相助。';
					break;
				case '克制':
					interpretation += '存在五行相克，表示可能遇到阻碍，需要谨慎应对。';
					break;
				default:
					interpretation += '卦象显示情况较为复杂，需要深入分析。';
			}
			
			return interpretation;
		},
		
		shareData() {
			return {
				type: 'result',
				title: this.hexagram ? `${this.question} - ${this.hexagram.name}` : '占卜结果',
				description: this.simpleInterpretation,
				hexagram: this.hexagram ? this.hexagram.toObject() : null,
				question: this.question,
				path: `/pages/divination-result/divination-result?type=${this.type}&question=${encodeURIComponent(this.question)}&hexagram=${encodeURIComponent(JSON.stringify(this.hexagram?.toObject() || {}))}`
			}
		}
	},
	onLoad(option) {
		this.initData(option);
		this.shareService = new ShareService();
	},
	methods: {
		initData(option) {
			console.log('DivinationResult - initData:', option);
			
			this.type = option.type || '';
			this.question = decodeURIComponent(option.question || '');
			
			// 解析后端API返回的结果数据
			if (option.result) {
				try {
					const resultData = JSON.parse(decodeURIComponent(option.result));
					console.log('DivinationResult - resultData:', resultData);
					
					// 处理后端返回的数据结构
					if (resultData.hexagram) {
						// 如果后端返回的是完整的卦象对象
						this.hexagram = Hexagram.fromObject(resultData.hexagram);
					} else if (resultData.hexagramName) {
						// 如果后端只返回卦象名称等基本信息，需要构造完整对象
						this.hexagram = this.createHexagramFromApiData(resultData);
					}
					
					console.log('DivinationResult - hexagram created:', this.hexagram);
				} catch (error) {
					console.error('解析结果数据失败:', error);
					console.error('原始数据:', option.result);
					
					// 显示错误提示
					uni.showToast({
						title: '结果数据解析失败',
						icon: 'none',
						duration: 3000
					});
				}
			} else if (option.hexagram) {
				// 兼容旧的数据格式
				try {
					const hexagramData = JSON.parse(decodeURIComponent(option.hexagram));
					console.log('DivinationResult - hexagramData:', hexagramData);
					
					this.hexagram = Hexagram.fromObject(hexagramData);
					console.log('DivinationResult - hexagram created:', this.hexagram);
				} catch (error) {
					console.error('解析卦象数据失败:', error);
					console.error('原始数据:', option.hexagram);
					
					// 显示错误提示
					uni.showToast({
						title: '卦象数据解析失败',
						icon: 'none',
						duration: 3000
					});
				}
			} else {
				console.warn('DivinationResult - 没有提供结果数据');
				uni.showToast({
					title: '缺少结果数据',
					icon: 'none',
					duration: 3000
				});
			}
			
			// 设置元信息
			this.setMetaInfo(option);
		},
		
		/**
		 * 从API数据创建卦象对象
		 */
		createHexagramFromApiData(apiData) {
			// 根据后端API返回的数据结构创建卦象对象
			return new Hexagram({
				name: apiData.hexagramName || apiData.name || '未知卦象',
				upperSymbol: apiData.upperSymbol || '☰',
				lowerSymbol: apiData.lowerSymbol || '☰',
				description: apiData.description || apiData.interpretation || '暂无描述',
				upperElement: apiData.upperElement || '金',
				lowerElement: apiData.lowerElement || '金'
			});
		},
		
		setMetaInfo(option) {
			switch (this.type) {
				case 'time':
					if (option.selectedTime) {
						this.metaInfo = `起卦时间: ${decodeURIComponent(option.selectedTime)}`;
					}
					break;
				case 'number':
					if (option.upperNumber && option.lowerNumber) {
						this.metaInfo = `选择数字: ${option.upperNumber} + ${option.lowerNumber}`;
					}
					break;
				case 'voice':
					this.metaInfo = '基于语音内容起卦';
					break;
				case 'photo':
					this.metaInfo = '基于图片信息起卦';
					break;
			}
		},
		
		viewHexagramDetail() {
			if (!this.hexagram) return;
			if (this.navigating) return;
			this.navigating = true;
			
			uni.navigateTo({
				url: `/pages/hexagram-detail/hexagram-detail?hexagram=${encodeURIComponent(JSON.stringify(this.hexagram.toObject()))}`,
				complete: () => {
					setTimeout(() => {
						this.navigating = false;
					}, 1000);
				}
			});
		},
		
		restartDivination() {
			uni.showModal({
				title: '重新起卦',
				content: '是否要重新开始占卜？',
				success: (res) => {
					if (res.confirm) {
						uni.navigateBack({
							delta: 2 // 返回到首页
						});
					}
				}
			});
		},
		
		shareResult() {
			if (!this.hexagram) {
				uni.showToast({
					title: '卦象数据不存在',
					icon: 'none'
				});
				return;
			}
			
			const shareContent = `我刚用"合一个"占卜了"${this.question}"，得到"${this.hexagram.name}"卦，${this.simpleInterpretation}`;
			
			// 在小程序中使用复制到剪贴板的方式分享
			uni.showActionSheet({
				itemList: ['复制文本', '取消'],
				success: (res) => {
					if (res.tapIndex === 0) {
						uni.setClipboardData({
							data: shareContent,
							success: () => {
								uni.showToast({
									title: '已复制到剪贴板'
								});
							}
						});
					}
				}
			});
		},
		
		// 分享相关方法
		handleShareToFriend() {
			console.log('分享给微信好友:', this.shareData)
			this.shareService.shareToFriend(this.shareData)
				.then(content => {
					uni.showToast({
						title: '分享成功',
						icon: 'success'
					})
					this.hideShareOptions()
				})
				.catch(error => {
					console.error('分享失败:', error)
					uni.showToast({
						title: '分享失败',
						icon: 'none'
					})
				})
		},
		
		handleShareToMoments() {
			console.log('分享到朋友圈:', this.shareData)
			this.shareService.shareToMoments(this.shareData)
				.then(content => {
					uni.showToast({
						title: '分享成功',
						icon: 'success'
					})
					this.hideShareOptions()
				})
				.catch(error => {
					console.error('分享失败:', error)
					uni.showToast({
						title: '分享失败',
						icon: 'none'
					})
				})
		},
		
		handleCopyLink() {
			console.log('复制链接:', this.shareData)
			this.shareService.copyShareLink(this.shareData)
				.then(content => {
					console.log('复制成功:', content)
					uni.showToast({
						title: '已复制到剪贴板',
						icon: 'success'
					})
					this.hideShareOptions()
				})
				.catch(error => {
					console.error('复制失败:', error)
					uni.showToast({
						title: '复制失败',
						icon: 'none'
					})
				})
		},
		
		handleGeneratePoster() {
			console.log('生成海报:', this.shareData)
			this.showShareTemplate = true
			this.shareTemplateType = 'elegant'
			
			// 延迟生成海报，确保模板已渲染
			setTimeout(() => {
				this.showCanvas = true
				this.$nextTick(() => {
					if (this.$refs.shareTemplate) {
						this.$refs.shareTemplate.generatePoster()
							.then(imagePath => {
								console.log('海报生成成功:', imagePath)
								uni.showToast({
									title: '海报已生成',
									icon: 'success'
								})
								// 可以保存到相册或分享
								this.shareService.saveImageToAlbum(imagePath)
									.then(() => {
										uni.showToast({
											title: '已保存到相册',
											icon: 'success'
										})
									})
									.catch(error => {
										console.error('保存到相册失败:', error)
										uni.showToast({
											title: '保存失败',
											icon: 'none'
										})
									})
							})
							.catch(error => {
								console.error('海报生成失败:', error)
								uni.showToast({
									title: '海报生成失败',
									icon: 'none'
								})
							})
							.finally(() => {
								this.showCanvas = false
								this.hideShareOptions()
							})
					}
				})
			}, 300)
		},
		
		showShareOptions() {
			if (!this.hexagram) {
				uni.showToast({
					title: '卦象数据不存在',
					icon: 'none'
				});
				return;
			}
			this.showShareModal = true;
		},
		
		hideShareOptions() {
			this.showShareModal = false;
		},
		
		closeShareTemplate() {
			this.showShareTemplate = false
			this.showCanvas = false
		}

	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	padding: 32rpx;
}

.content {
	padding-top: 40rpx;
}

.result-header {
	text-align: center;
	margin-bottom: 48rpx;
	
	.result-title {
		display: block;
		font-size: 48rpx;
		font-weight: bold;
		color: #000000;
		margin-bottom: 8rpx;
	}
	
	.result-subtitle {
		display: block;
		font-size: 28rpx;
		color: rgba(0, 0, 0, 0.7);
	}
}

.question-display {
	.question-label {
		display: block;
		font-size: 28rpx;
		color: rgba(0, 0, 0, 0.7);
		margin-bottom: 16rpx;
	}
	
	.question-text {
		display: block;
		font-size: 32rpx;
		color: #000000;
		line-height: 1.5;
		margin-bottom: 16rpx;
	}
	
	.question-meta {
		display: block;
		font-size: 24rpx;
		color: #6A82FB;
	}
}

.hexagram-display {
	.hexagram-visual {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
		
		.hexagram-symbols {
			margin-right: 32rpx;
			
			.symbol-text {
				font-size: 80rpx;
				line-height: 1;
			}
		}
		
		.hexagram-info {
			flex: 1;
			
			.hexagram-name {
				display: block;
				font-size: 36rpx;
				font-weight: bold;
				color: #000000;
				margin-bottom: 8rpx;
			}
			
			.element-relation {
				display: block;
				font-size: 28rpx;
				color: #6A82FB;
			}
		}
	}
	
	.hexagram-description {
		margin-bottom: 24rpx;
		
		.description-text {
			font-size: 30rpx;
			color: #000000;
			line-height: 1.6;
		}
	}
	
	.view-detail-hint {
		text-align: right;
		
		.hint-text {
			font-size: 24rpx;
			color: rgba(0, 0, 0, 0.7);
		}
	}
}

.interpretation {
	.interpretation-title {
		display: block;
		font-size: 32rpx;
		font-weight: 500;
		color: #000000;
		margin-bottom: 24rpx;
	}
	
	.interpretation-text {
		font-size: 30rpx;
		color: #000000;
		line-height: 1.6;
	}
}

.actions {
	margin-top: 48rpx;
	display: flex;
	flex-direction: column;
	gap: 32rpx;
	
	.primary-action {
		.action-button {
			background: linear-gradient(135deg, #6A82FB 0%, #FC5C7D 100%);
			color: white;
			box-shadow: 0 8rpx 32rpx rgba(106, 130, 251, 0.3);
			
			&:active {
				transform: scale(0.98);
				box-shadow: 0 4rpx 16rpx rgba(106, 130, 251, 0.2);
			}
			
			&.disabled {
				background: linear-gradient(135deg, #ccc 0%, #999 100%);
				box-shadow: none;
				
				.button-content {
					opacity: 0.6;
				}
			}
			
			.button-arrow {
				color: rgba(255, 255, 255, 0.8);
				font-size: 32rpx;
				font-weight: bold;
			}
		}
	}
	
	.secondary-actions {
		display: flex;
		gap: 24rpx;
		
		.action-button {
			flex: 1;
			background: rgba(255, 255, 255, 0.9);
			color: #333;
			border: 2rpx solid rgba(106, 130, 251, 0.2);
			box-shadow: 0 4rpx 16rpx rgba(106, 130, 251, 0.1);
			
			&:active {
				transform: scale(0.98);
				background: rgba(106, 130, 251, 0.05);
			}
			
			&.disabled {
				background: rgba(255, 255, 255, 0.5);
				border-color: rgba(0, 0, 0, 0.1);
				
				.button-content {
					opacity: 0.5;
				}
			}
		}
	}
	
	.action-button {
		display: flex;
		align-items: center;
		padding: 32rpx 24rpx;
		border-radius: 24rpx;
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;
		
		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: -100%;
			width: 100%;
			height: 100%;
			background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
			transition: left 0.5s ease;
		}
		
		&:active::before {
			left: 100%;
		}
		
		.button-icon {
			font-size: 48rpx;
			margin-right: 24rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 80rpx;
			height: 80rpx;
			border-radius: 16rpx;
			background: rgba(255, 255, 255, 0.1);
		}
		
		.button-content {
			flex: 1;
			display: flex;
			flex-direction: column;
			
			.button-title {
				font-size: 32rpx;
				font-weight: 600;
				margin-bottom: 8rpx;
				line-height: 1.2;
			}
			
			.button-desc {
				font-size: 24rpx;
				opacity: 0.8;
				line-height: 1.3;
			}
		}
	}
}

/* 分享弹窗样式 */
.share-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 1000;
	
	.share-content {
		width: 100%;
		background: white;
		border-radius: 32rpx 32rpx 0 0;
		padding: 48rpx 32rpx 64rpx;
		animation: slideUp 0.3s ease;
		
		.share-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 48rpx;
			
			.share-title {
				font-size: 36rpx;
				font-weight: 600;
				color: #333;
			}
			
			.close-btn {
				width: 64rpx;
				height: 64rpx;
				border-radius: 50%;
				background: rgba(0, 0, 0, 0.1);
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				color: #666;
				
				&:active {
					background: rgba(0, 0, 0, 0.2);
				}
			}
		}
		
		.share-options {
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 32rpx;
			
			.share-option {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 24rpx 16rpx;
				border-radius: 20rpx;
				transition: all 0.3s ease;
				
				&:active {
					background: rgba(106, 130, 251, 0.1);
					transform: scale(0.95);
				}
				
				.share-icon {
					font-size: 64rpx;
					margin-bottom: 16rpx;
					width: 96rpx;
					height: 96rpx;
					border-radius: 24rpx;
					background: linear-gradient(135deg, rgba(106, 130, 251, 0.1) 0%, rgba(252, 92, 125, 0.1) 100%);
					display: flex;
					align-items: center;
					justify-content: center;
				}
				
				.share-text {
					font-size: 24rpx;
					color: #666;
					text-align: center;
				}
			}
		}
	}
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

.error-display {
	text-align: center;
	padding: 40rpx 0;
	
	.error-text {
		font-size: 30rpx;
		color: rgba(0, 0, 0, 0.7);
		line-height: 1.6;
	}
}
</style>